package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetMemberResponse;
import com.woyao.core.model.Member;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;


public class MemberActivity extends AppCompatActivity {

    private TextView mytitle;
    private TextView org;
    private TextView descTxt;
    RadioGroup status;

    private  Button nextBtn;
    Button deleteBtn;
    Button demandBtn;

    boolean changed = false;
    Button manageOrg;

    ProgressDialog progressDialog;
    Member mem = new Member();
    private boolean loading = false;

    Integer id = 0;

    private Integer ORG_CODE = 300;
    private Integer TITLE_CODE = 400;
    private Integer DESC_CODE = 600;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        org = (TextView) findViewById(R.id.id_organization);
        status = (RadioGroup) findViewById(R.id.id_member_status);

        status.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                if (!loading) {

                    changed = true;
                    if (i == R.id.id_member_apply) {
                        mem.setStatus("apply");
                    }
                    if (i == R.id.id_member_ongoing) {
                        mem.setStatus("ongoing");
                    }
                    if (i == R.id.id_member_ever) {
                        mem.setStatus("ever");
                    }
                    if (id > 0 ){
                        Common.setMemberAttr(mem.getId(),"status",mem.getStatus());
                    }
                }
            }
        });

        mytitle = (TextView) findViewById(R.id.my_member_title);

        mytitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editTitle();
            }
        });



        descTxt = (TextView) findViewById(R.id.id_member_desc);

        descTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type", "member_desc");
                intent.putExtra("content", mem.getDescription());

                intent.setClass(MemberActivity.this, InputActivity.class);
                startActivityForResult(intent, DESC_CODE);
            }
        });


        demandBtn = (Button) findViewById(R.id.publish_demand);
        demandBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from", "chance"  );
                intent.putExtra("is_new", true);
                intent.putExtra("member_id", id);
                intent.putExtra("member_title", mem.getOrgtitle() + "-"+ mem.getTitle());
                intent.setClass(MemberActivity.this, DemandNewActivity.class);
                startActivity(intent);
            }
        });

        manageOrg = (Button) findViewById(R.id.manage_org);
        manageOrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();

                intent.putExtra("id", mem.getOrg_id());

                intent.setClass(MemberActivity.this, OrgActivity.class);
                startActivity(intent);


            }
        });
        Button setDefaultBtn = (Button)findViewById(R.id.member_setdefault);
        setDefaultBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.setProfileAttrFeedback(MemberActivity.this, "member_id", mem.getId() +"");
            }
        });

        deleteBtn = (Button) findViewById(R.id.delete_member);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
                        setTitle("信息").
                        setMessage("删除吗！").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteMember();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();


            }
        });



        nextBtn = (Button) findViewById(R.id.member_next);

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                addIt();

            }
        });

        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);


        if (id == 0) {

            mem.setOrgtitle( intent.getStringExtra("org_title"));
            mem.setOrg_id(intent.getIntExtra("org_id",0) );
            org.setText(mem.getOrgtitle());
            manageOrg.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);
            demandBtn.setVisibility(View.GONE);
            setDefaultBtn.setVisibility(View.GONE);
//            status.getChildAt(0).setVisibility(View.GONE);

            this.setTitle("添加组织");
        }else{

            loadData();
        }



    }


private void addIt(){
    if (mem.getTitle().equals("")) {
        Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
                setTitle("信息").
                setMessage("请填写组织身份").
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editTitle();
                    }
                }).
                create();
        alertDialog.show();

        return;
    }


    if (id==0 ) {
        addMember();
    }else {
        Intent intent = new Intent();
        intent.putExtra("member_id", mem.getId());
        intent.putExtra("member_title",   mem.getOrgtitle()+ " " + mem.getTitle());
        intent.putExtra("changed", changed);
        setResult(666, intent);
        finish();
    }
}
    private void editTitle(){
        Intent intent = new Intent();
        intent.putExtra("type", "role");
        intent.putExtra("content", mem.getTitle());

        intent.setClass(MemberActivity.this, InputActivity.class);
        startActivityForResult(intent, TITLE_CODE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed);
        intent.putExtra("member_id", mem.getId());
        intent.putExtra("member_title",   mem.getOrgtitle()+ " " + mem.getTitle());
        setResult(0, intent);
        finish();
        return true;
    }


    private void deleteMember() {

        changed = true;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在删除······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> needTask = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.deleteMember(userId, id);
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ){
                    if ( response.isSuccess()) {
                        Common.alert(MemberActivity.this, "已经删除");
                        Intent intent = new Intent();
                        intent.putExtra("changed", changed);
                        intent.putExtra("member_id", mem.getId());
                        intent.putExtra("member_title",   mem.getOrgtitle()+ " " + mem.getTitle());
                        setResult(666, intent);
                        finish();
                    }else{
                        Common.alert(MemberActivity.this, response.getMessage());
                    }
                }else{
                    Common.alert(MemberActivity.this, "系统发生错误");
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }



    private void loadData() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetMemberResponse> needTask = new AsyncTask<Void, Void, GetMemberResponse>() {
            @Override
            protected GetMemberResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMemberResponse> responseCall = svc.getMember(userId, id);
                try {
                    GetMemberResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final GetMemberResponse response) {
                if (response != null && response.getContent() != null) {
                    mem = response.getContent();

                    renderIt();
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }

    //    BusinessSelect select;
    private void renderIt() {
        loading = true;
        this.setTitle(mem.getOrgtitle());

        if (mem.getStatus().equals("ever")) {
            status.check(R.id.id_member_ever);
        } else if (mem.getStatus().equals("ongoing")) {
            status.check(R.id.id_member_ongoing);
        } else {
            status.check(R.id.id_member_apply);
        }
        if ( !mem.getTitle().equals("") ) {
            mytitle.setText(mem.getTitle());
            mytitle.setTextColor(Color.BLACK);
        }

        if ( !mem.getDescription().equals("") ) {
            descTxt.setText(mem.getDescription());
            descTxt.setTextColor(Color.BLACK);
        }

        if (mem.getAdmin() > 0){
            manageOrg.setVisibility(View.VISIBLE);
        }else{
            manageOrg.setVisibility(View.GONE);
        }


        if ( !mem.getOrgtitle().equals("") ) {
            org.setText(mem.getOrgtitle());
            org.setTextColor(Color.BLACK);
        }



     loading = false;


    }


    private  void addMember(){



//        if (selfEmployCheck.isChecked()) {
//            mem.setSelf_employed( 1);
//        }else{
//            mem.setSelf_employed( 0);
//        }

//        if( mem.getOrgtitle().equals("")) {
//
//            Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
//                    setTitle("信息").
//                    setMessage("请填写组织名称").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent();
//                            intent.putExtra("type", "orgtitle");
//                            intent.putExtra("content", mem.getOrgtitle());
//                            intent.setClass(MemberActivity.this, InputActivity.class);
//                            startActivityForResult(intent, ORG_CODE);
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

//        if( mem.getTitle().equals("")) {
//
//            Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
//                    setTitle("信息").
//                    setMessage("请填写职务名称").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent();
//                            intent.putExtra("type", "role");
//                            intent.putExtra("content", mem.getTitle());
//
//                            intent.setClass(MemberActivity.this, InputActivity.class);
//                            startActivityForResult(intent, TITLE_CODE);
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }


//        if( mem.getBusiness().equals("")) {
//
//            Dialog alertDialog = new AlertDialog.Builder(MemberActivity.this).
//                    setTitle("信息").
//                    setMessage("请选择所在行业").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent();
//                            intent.putExtra("type", "role");
//                            intent.putExtra("content", mem.getTitle());
//
//                            intent.setClass(MemberActivity.this, ConfirmBusiness.class);
//                            startActivityForResult(intent, BUSINESS_CODE);
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("正在添加······");
            progressDialog.show();



            AsyncTask<Void,Void,BaseResponse> task =
                    new AsyncTask<Void, Void, BaseResponse>() {
                        @Override
                        protected BaseResponse doInBackground(Void... params) {
                            AccountService svc = ServiceFactory.get(AccountService.class);
                            Call<BaseResponse> responseCall = svc.addMember(userId,mem.getOrg_id(),mem.getOrgtitle(),mem.getTitle(),mem.getStatus(),mem.getDescription());
                            try {
                                BaseResponse response = responseCall.execute().body();
                                return response;
                            } catch (IOException e) {
                                e.printStackTrace();
                                return null;
                            }
                        }
                        @Override
                        protected void onPostExecute(final BaseResponse response) {
                            progressDialog.dismiss();
                            if ( response.isSuccess()){
                                    Intent intent = new Intent();
                                    intent.putExtra("member_id", Integer.parseInt( response.getMessage()));
                                    intent.putExtra("member_title",   mem.getOrgtitle()+ " " + mem.getTitle());
                                    intent.putExtra("changed", true);
                                    setResult(666, intent);
                                    finish();
                            }else{
                                Common.alert(MemberActivity.this,response.getMessage());
                            }
                        }
                        @Override
                        protected void onCancelled() {
                            progressDialog.dismiss();
                        }
                    };
            task.execute();

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TITLE_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");
            changed = true;
            mem.setTitle( con.toString());
            mytitle.setText(con);
            mytitle.setTextColor(Color.BLACK);

            if ( id > 0 ) Common.setMemberAttr(id, "title", con.toString());

        }  else if (requestCode == DESC_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");
            changed = true;
            mem.setDescription( con.toString());
            descTxt.setText(con);
            descTxt.setTextColor(Color.BLACK);

            if ( id > 0 ) Common.setMemberAttr(id, "description", mem.getDescription());

        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("member_id", mem.getId());
            intent.putExtra("member_title",   mem.getOrgtitle()+ " " + mem.getTitle());
            intent.putExtra("changed", false);
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}